package cn.com.fattiger.framework.cms.config;

import freemarker.template.Configuration;
import freemarker.template.TemplateExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.servlet.MultipartConfigElement;
import java.io.File;

/**
 * Created by Administrator on 2016/1/8.
 */
@org.springframework.context.annotation.Configuration
public class FreemarkerConfig {

    @Autowired
    private CustomConfig customConfig;

    @Bean
    @Scope(value = "singleton")
    public Configuration templateConfiguration() throws Exception {
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
        cfg.setDirectoryForTemplateLoading(new File(customConfig.getTemplateRoot()));
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        return cfg;
    }

    /**
     * 覆盖springboot自带默认配置
     */
    @Bean
    public FreeMarkerConfigurer freeMarkerConfigurer() throws Exception {
        FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
        cfg.setDirectoryForTemplateLoading(new File(customConfig.getTemplateRoot()));
        cfg.setTemplateUpdateDelay(5);
        configurer.setConfiguration(cfg);

        return configurer;
    }

    @Bean
    @Scope(value = "singleton")
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setMaxFileSize("10240KB");
        factory.setMaxRequestSize("10240KB");
        return factory.createMultipartConfig();
    }
}
